package com.world.rickcloudendpoint.api.controller;

import cn.hutool.core.lang.Assert;
import com.world.rickcloudendpoint.common.Result;
import com.world.rickcloudendpoint.common.ResultCode;
import com.world.rickcloudendpoint.common.annotation.UserActionLogger;
import com.world.rickcloudendpoint.common.constant.DetailErrorCodes;
import com.world.rickcloudendpoint.common.constant.ErrorCodes;
import com.world.rickcloudendpoint.common.constant.SymbolConstants;
import com.world.rickcloudendpoint.common.exception.ClientException;
import com.world.rickcloudendpoint.common.exception.ModuleException;
import com.world.rickcloudendpoint.logic.service.IASignalService;
import com.world.rickcloudendpoint.models.params.QueryParams;
import com.world.rickcloudendpoint.models.params.common.PageBy;
import com.world.rickcloudendpoint.models.params.common.QueryWhere;
import com.world.rickcloudendpoint.models.params.common.SortBy;
import com.world.rickcloudendpoint.models.result.PageResult;
import com.world.rickcloudendpoint.models.vo.ASignalVO;
import com.world.rickcloudendpoint.service.tools.AggregateQueryTools;
import io.swagger.annotations.ApiParam;
import lombok.extern.log4j.Log4j2;
import org.apache.commons.lang3.StringUtils;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.validation.constraints.Min;
import javax.validation.constraints.NotNull;
import java.util.List;

/**
 * @description: a 信号外部访问接口
 * @author: jlsong
 * @date: 2022/01/22 22:16:27
 * @version: 1.0
 */
@Log4j2
@RestController
public class ASignalController implements ASignalApi {

    final IASignalService aSignalService;

    public ASignalController(IASignalService aSignalService) {
        this.aSignalService = aSignalService;
    }

    @UserActionLogger(title = "用户增加A信号", businessType = "新增")
    @Override
    public Result<ASignalVO> addASignal(ASignalVO payload) throws ClientException, ModuleException {
        // TODO 校验 参数
        if (payload == null) {
            throw new ClientException(ErrorCodes.getApplicationUi(DetailErrorCodes.Request_Param_Null.value()), DetailErrorCodes.Request_Param_Null.getReasonPhrase());
        }
        // TODO 校验参数体的一些属性值是否唯一
        return Result.ok(aSignalService.add(payload));

    }

    @Override
    public Result<ASignalVO> editASignal(ASignalVO payload) throws ClientException, ModuleException {
        if (payload == null) {
            throw new ClientException(ErrorCodes.getApplicationUi(DetailErrorCodes.Request_Param_Null.value()), DetailErrorCodes.Request_Param_Null.getReasonPhrase());
        }
        if (StringUtils.isBlank(payload.getId())) {
            throw new ClientException(ErrorCodes.getApplicationUi(DetailErrorCodes.Request_Param_Null.value()), DetailErrorCodes.Request_Param_Null.getReasonPhrase());
        }
        return Result.ok(aSignalService.edit(payload));
    }

    @Override
    public Result<Long> delASignals(String ids) throws ClientException, ModuleException {
        Assert.notBlank(ids, "参数ids为空");
        String[] idArr = ids.split(SymbolConstants.COMMA);
        Long ret = aSignalService.del(idArr);
        if (ret == -1L) {
            return Result.fail(ResultCode.FAIL);
        }
        return Result.ok(ret);
    }

    @Override
    public Result<Object> addASignals(List<ASignalVO> payload) throws ClientException, ModuleException {
        Assert.noNullElements(payload.toArray(), "批量增加的实体集合不能为空");
        boolean ret = aSignalService.addBatch(payload, payload.size());
        return ret ? Result.ok(null) : Result.fail(ResultCode.FAIL);
    }

    @Override
    public Result<Object> listASignals(@ApiParam(value = "查询过滤表达式，例如:((a|b)&c)|((a&b&d)|e)") @RequestParam(value = "exp", required = false) String exp,
                                       @ApiParam("查询过滤表达式对应字典sql，例如：{\"a\": $dsl};{\"b\": $dsl};{\"c\": $dsl};{ \"d\": $dsl};{\"'e\": $dsl}....。说明：$dsl->{\"field\": \"id\", \"op\": \"eq|ne|gt|lt|gte|lte|in|nin|like\", '\"value\": int|float|long|double|string}") @RequestParam(value = "dsl", required = false) String dsl,
                                       @Min(0) @ApiParam(value = "结果列表偏移量", defaultValue = "0") @RequestParam(value = "offset", required = false, defaultValue = "0") Long offset,
                                       @Min(-1) @ApiParam(value = "预期获取数量,最小值-1表示获取全部", defaultValue = "200") @RequestParam(value = "size", required = false, defaultValue = "200") Integer size,
                                       @NotNull @ApiParam(value = "排序字段，默认为添加时间倒序，排序方式:asc|desc，默认倒序desc，默认使用'；'分割，例如：[{\"field\": \"id\", \"by\": \"desc\" },{\"field\": \"name\", \"by\": \"asc\"}...]") @RequestParam(value = "sorts", required = false) String sorts) throws ClientException, ModuleException {
        QueryParams params = new QueryParams();
        // 组装排序
        List<SortBy> sortByList = AggregateQueryTools.parseSortsStr(sorts);
        if (sortByList != null && sortByList.size() > 0) {
            params.setSorts(sortByList);
        }
        // 组装分页
        PageBy pageBy = AggregateQueryTools.parsePageOptions(offset, size);
        if (pageBy != null) {
            params.setPage(pageBy);
        }
        // 组装查询条件
        QueryWhere where = AggregateQueryTools.parseFilterCriteriaOptions(exp, dsl);
        if (where != null) {
            params.setWhere(where);
        }
        PageResult<ASignalVO> result = aSignalService.list(null, params);
        return Result.ok(result);
    }
}
